<?php


namespace NanQi\Hope;


use Hyperf\Contract\ApplicationInterface;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\ContainerInterface;
use NanQi\Hope\Constants\ConfigConstants;

class App
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * App constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->config = $this->container->get(ConfigInterface::class);
    }

    /**
     * Run the application.
     */
    public function run()
    {
        $application = $this->container->get(ApplicationInterface::class);
        $application->run();
    }

    /**
     * Config the application using arrays.
     * @param array $configs
     * @param int $flag
     */
    public function config(array $configs, int $flag = ConfigConstants::CONFIG_MERGE)
    {
        foreach ($configs as $key => $value) {
            $this->addConfig($key, $value, $flag);
        }
    }

    private function addConfig(string $key, $configValues, $flag)
    {
        $config = $this->config->get($key);

        if (! is_array($config)) {
            $this->config->set($key, $configValues);
            return;
        }

        if ($flag === ConfigConstants::CONFIG_MERGE) {
            $this->config->set($key, array_merge_recursive($config, $configValues));
        } else {
            $this->config->set($key, array_merge($config, $configValues));
        }
    }
}